import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from "./routes";
import store from "@/store"
import {isEmptyObject} from "ant-design-vue/lib/vc-form/src/utils";

Vue.use(VueRouter)

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
router.beforeEach(((to, from, next) => {
    //载入缓存数据
    _loadLocalStorageCache();
    //验证路由权限
    _verifyRoute(to.path);
    //未登录跳转到登录页面
    if (!localStorage.token && to.name !== 'login') {
        next({name: 'login'})
    } else {
        next()
    }
}))

function _loadLocalStorageCache() {
    //首次进入系统加载上次登录授权的菜单数据
    if (localStorage.menus && store.state.app.appMenuList.length === 0) {
        store.commit("setAppMenuList", JSON.parse(localStorage.menus))
    }
    //权限路由缓存数据
    if (localStorage.routesCacheByPath && isEmptyObject(store.state.app.routesCacheByPath)) {
        store.commit("setRoutesCacheByPath", JSON.parse(localStorage.routesCacheByPath))
    }
}

function _verifyRoute(path) {
    let state = Boolean(store.state.app.routesCacheByPath[path]);
    const overlookRoute = ['/login'];
    //忽略路由
    if (overlookRoute.includes(path)) {
        state = true;
    }
    store.commit('setAuthPage', state)
}

export default router
